<?php
/** 
	此类需要经常更新。更新所有的公共方法
	vane 提供的部分公共方法
	其中某些lib框架会用到这些方法，请不要删除
*/

/**
	模板输出方法
 */
function t($templateFilePath,$arr=array()) {
	static $tpl = null;
	if(is_null($tpl)){
		$tpl = new Smarty();
		$tpl->template_dir = VANE_SMARTY_TEMPLATE_DIR;
		$tpl->compile_dir = VANE_SMARTY_COMPILE_DIR;
		$tpl->config_dir = VANE_SMARTY_CONFIG_DIR;
		$tpl->cache_dir = VANE_SMARTY_CACHE_DIR;
		$tpl->debugging = false;
		$tpl->caching=VANE_DEBUG;
		$tpl->cache_lifetime=60*60*24;
		$tpl->left_delimiter = '{';
		$tpl->right_delimiter = '}';
		if (VANE_DEBUG) {
			$tpl->force_compile = true;
		} else {
			$tpl->compile_check = false;
		}
		$tpl->register_function('u','smartyU');
 		$tpl->register_prefilter('smartyPrefilter');
	}
	if (! is_null ( $arr ) && is_array ( $arr )) {
		while ( list ( $key, $val ) = each ( $arr ) ) {
			$tpl->assign ( $key, $val );
		}
	}
	$tpl->display ( $templateFilePath, md5 ( $_SERVER ['REQUEST_URI'] ) );
}

/**
	生成URL的方法
 */
function u($url) {
	return Router::getInstance()->buildURI($url);
}

/**
	获取缓存对象
 */
function c() {
	static $cache = null;
	if (is_null ( $cache )) {
		$cache = new secache ();
		$cache->workat(VANE_SECACHE_PATH.DS.'cachedata');
	}
	return $cache;
}

/**
 * 获取缓存值
 */
function getCache($key) {
	$value = null;
	c()->fetch ( md5 ( $key ), $value );
	return $value;
}

/**
 * 设置缓存
 */
function setCache($key, $value) {
	c()->store ( md5 ( $key ), $value );
}

/**
 * 删除缓存
 */
function delCache($key) {
	c()->delete ( md5 ( $key ) );
}

/**
	smarty框架的生成url标签
 */
function smartyU($params,&$smarty){
	return u($params['val']);
}

/**
	smarty编译前调用的方法，删除所有的页面空格，并涉及到css、js、页面压缩
 */
function smartyPrefilter($out_put,&$smarty) {
	if(VANE_DEBUG){
		return $out_put;
	}

	//启用css、js压缩，需要引用csstidy、JavaScriptPacker等类库

	//require_once("./libs/class.JavaScriptPacker.php");
	//require_once("./libs/csstidy/class.csstidy.php");

	
	//mkdirs('./static/packer/');
	//// 前置link,压缩css
	//if (preg_match_all('/<link.*?href=[\'"]*([^\'"]+)[\'"]*.*?\/>/', $out_put, $regs)){
		//$tidy = new csstidy();
		//$tidy->set_cfg('remove_last_;', true);
		//$tidy->load_template('highest_compression');
		//foreach ($regs[1] as $key => $val){
			//if (strpos($val, '.css') !== false){
				//$dir = dirname($val);
				//$name = basename($val, '.css');
				//$css_code = file_get_contents('./' . $val);//获取到根目录下（./）的css文件并读取
				//$pack_css = 'static/packer/'. $name . '.pack.css';//压缩之后放的css文件
				//$tidy->parse($css_code);
				//if (file_put_contents('./'.$pack_css, $tidy->print->plain())){
					//$out_put = str_replace($val, $pack_css, $out_put);
				//}
			//}
		//}
	//}
	//压缩js
	// 这里做了一些处理,只匹配非http开头的script标签
	/*if (preg_match_all('%<script.*?src=[\'"]*(?!http:)([^\'"]+)[\'"]*.*?></script>%',$out_put, $regs)){
		////foreach ($regs as $key => $val){
			////$regs[$key] = array_unique($val);
		////}
		////foreach ($regs[0] as $key => $val){
			////$dir = dirname($regs[1][$key]);
			////$name = basename($regs[1][$key], '.js');
			////$js_code = file_get_contents('./' . $regs[1][$key]);
			////$pack_js = 'static/packer/' . $name . '.pack.js';//压缩之后放的css文件
			////$pack = new JavaScriptPacker($js_code);
			////if (file_put_contents('./'.$pack_js, $pack->pack())){
				////$out_put = str_replace($regs[1][$key], $pack_js, $out_put);
			////}
		////}
	//}*/
	
    // 去掉html注释
    $out_put = preg_replace('/<!--[^!]*-->/', '', $out_put);
    // 压缩html代码,去掉行首尾空格及换行
    //$out_put = preg_replace('/\s*[\n\r\t]*\s*/',' ',$out_put);
	$out_put = preg_replace('/\s+/',' ',$out_put);

	return $out_put;
}

/**
	创建多级目录
 */
function mkdirs($dir){
	if(!is_dir($dir)){
		if(!mkdirs(dirname($dir))){
			return false;
		}
		if(!mkdir($dir,0777)){
			return false;
		}
	}
	return true;  
}

function replaceStr($str,$rstr,$mode=true) {
	if(empty($str) || empty($rstr)){
		return $str;
	}
	$index = 0;
	if($mode){
		$index = strpos($str,$rstr);
	}
	else{
		$index = strrpos($str,$rstr);
	}
	return substr_replace($str,'',$index,strlen($rstr));
}

/**
	简化引入其他php文件的代码
 */
function import($filePath) {
	require_once(VANE_PATH.$filePath);
}
function importApp($filePath) {
	import('app'.DS.$filePath);
}

/**
	重定向
 */
function redirect($url) {
	header("Location: ".$url); 
}

/** 
* HTTP Protocol defined status codes 
* HTTP协议状态码,调用函数时候只需要将$num赋予一个下表中的已知值就直接会返回状态了。 
* @param int $num 
*/ 
function https($num) { 
	$http = array ( 
	100 => "HTTP/1.1 100 Continue", 
	101 => "HTTP/1.1 101 Switching Protocols", 
	200 => "HTTP/1.1 200 OK", 
	201 => "HTTP/1.1 201 Created", 
	202 => "HTTP/1.1 202 Accepted", 
	203 => "HTTP/1.1 203 Non-Authoritative Information", 
	204 => "HTTP/1.1 204 No Content", 
	205 => "HTTP/1.1 205 Reset Content", 
	206 => "HTTP/1.1 206 Partial Content", 
	300 => "HTTP/1.1 300 Multiple Choices", 
	301 => "HTTP/1.1 301 Moved Permanently", 
	302 => "HTTP/1.1 302 Found", 
	303 => "HTTP/1.1 303 See Other", 
	304 => "HTTP/1.1 304 Not Modified", 
	305 => "HTTP/1.1 305 Use Proxy", 
	307 => "HTTP/1.1 307 Temporary Redirect", 
	400 => "HTTP/1.1 400 Bad Request", 
	401 => "HTTP/1.1 401 Unauthorized", 
	402 => "HTTP/1.1 402 Payment Required", 
	403 => "HTTP/1.1 403 Forbidden", 
	404 => "HTTP/1.1 404 Not Found", 
	405 => "HTTP/1.1 405 Method Not Allowed", 
	406 => "HTTP/1.1 406 Not Acceptable", 
	407 => "HTTP/1.1 407 Proxy Authentication Required", 
	408 => "HTTP/1.1 408 Request Time-out", 
	409 => "HTTP/1.1 409 Conflict", 
	410 => "HTTP/1.1 410 Gone", 
	411 => "HTTP/1.1 411 Length Required", 
	412 => "HTTP/1.1 412 Precondition Failed", 
	413 => "HTTP/1.1 413 Request Entity Too Large", 
	414 => "HTTP/1.1 414 Request-URI Too Large", 
	415 => "HTTP/1.1 415 Unsupported Media Type", 
	416 => "HTTP/1.1 416 Requested range not satisfiable", 
	417 => "HTTP/1.1 417 Expectation Failed", 
	500 => "HTTP/1.1 500 Internal Server Error", 
	501 => "HTTP/1.1 501 Not Implemented", 
	502 => "HTTP/1.1 502 Bad Gateway", 
	503 => "HTTP/1.1 503 Service Unavailable", 
	504 => "HTTP/1.1 504 Gateway Time-out"); 
	header($http[$num]);
	exit();
} 

function getRequestURL() {
	$scriptRequestDir = replaceStr($_SERVER['URL'],basename($_SERVER['SCRIPT_FILENAME']),false);
	if($scriptRequestDir == '/'){
		return $_SERVER['REQUEST_URI'];
	}
	$script = replaceStr($_SERVER['REQUEST_URI'],$scriptRequestDir);
	return '/'.$script;
}

/**
 * 生成验证码
 *
 * @param $num 生成几个数        	
 * @param $size 显示大小        	
 * @param $width 宽度        	
 * @param $height 高度
 *        	通过获取session的VerifyCode属性获取当前验证码
 */
function vCode($num = 4, $size = 20, $width = 0, $height = 0) {
	! $width && $width = $num * $size * 4 / 5 + 5;
	! $height && $height = $size + 10;
	// 去掉了 0 1 O l 等
	$str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW";
	$code = '';
	for($i = 0; $i < $num; $i ++) {
		$code .= $str [mt_rand ( 0, strlen ( $str ) - 1 )];
	}
	// 画图像
	$im = imagecreatetruecolor ( $width, $height );
	// 定义要用到的颜色
	$back_color = imagecolorallocate ( $im, 235, 236, 237 );
	$boer_color = imagecolorallocate ( $im, 118, 151, 199 );
	$text_color = imagecolorallocate ( $im, mt_rand ( 0, 200 ), mt_rand ( 0, 120 ), mt_rand ( 0, 120 ) );
	// 画背景
	imagefilledrectangle ( $im, 0, 0, $width, $height, $back_color );
	// 画边框
	imagerectangle ( $im, 0, 0, $width - 1, $height - 1, $boer_color );
	// 画干扰线
	for($i = 0; $i < 15; $i ++) {
		$font_color = imagecolorallocate ( $im, mt_rand ( 0, 255 ), mt_rand ( 0, 255 ), mt_rand ( 0, 255 ) );
		imagearc ( $im, mt_rand ( - $width, $width ), mt_rand ( - $height, $height ), mt_rand ( 30, $width * 2 ), mt_rand ( 20, $height * 2 ), 

		mt_rand ( 0, 360 ), mt_rand ( 0, 360 ), $font_color );
	}
	// 画干扰点
	for($i = 0; $i < 250; $i ++) {
		$font_color = imagecolorallocate ( $im, mt_rand ( 0, 255 ), mt_rand ( 0, 255 ), mt_rand ( 0, 255 ) );
		imagesetpixel ( $im, mt_rand ( 0, $width ), mt_rand ( 0, $height ), $font_color );
	}
	// 画验证码
	@imagefttext ( $im, $size, 0, 5, $size + 3, $text_color, './simsun.ttc', $code );
	ob_start ();
	header ( "Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate" );
	header ( "Content-type: image/png;charset=utf-8" );
	$_SESSION ["VerifyCode"] = $code;
	imagepng ( $im );
	imagedestroy ( $im );
	ob_flush ();
}

/**
 * 获取当前时间公共方法
 */
function current_date() {
	date_default_timezone_set ( 'Etc/GMT-8' );
	return date ( 'Y-m-d H:i:s' );
}

// 验证登录名
function regLoginName($str) {
	return preg_match ( "/^[a-zA-Z][a-zA-Z0-9_]{5,30}$/", $str );
}

// 验证数据库名称6-30位字母或下划线开头,只包括字母数字下划线
function reg_db_name($str) {
	return preg_match ( "/^[a-zA-Z_][a-zA-Z0-9_]{5,30}$/", $str );
}

// 验证密码
function regUserPass($str) {
	return preg_match ( '/^\S{8,30}$/', $str );
}

// 验证姓名
function regUserName($str) {
	return preg_match ( "/^[\x{4e00}-\x{9fa5}]+$/u", $str );
}

// 验证邮箱
function regUserMail($str) {
	return preg_match ( "/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/", $str );
}

// 验证手机号
function regUserMobile($str) {
	return preg_match ( "/^1[3|4|5|8][0-9]\d{4,8}$/", $str );
}

// 验证邮编
function regUserPostal($str) {
	return preg_match ( "/^[1-9][0-9]{5}$/", $str );
}

// 验证qq
function regUserQQ($str) {
	return preg_match ( "/^[0-9]{5,11}$/", $str );
}

// 验证固定电话
function regUserTelphone($str) {
	if ($str == "" || is_null ( $str )) {
		return true;
	}
	// 3-4位区号，7-8位直播号码，1－4位分机号
	return preg_match ( "/^\\d{3,4}-\\d{7,8}(-\d{1,4}){0,1}$/", $str );
}

// 验证身份证
function validationFilterIdCard($id_card) {
	if (strlen ( $id_card ) == 18) {
		return idcardChecksum18 ( $id_card );
	} else if ((strlen ( $id_card ) == 15)) {
		$id_card = idcard15to18 ( $id_card );
		return idcardChecksum18 ( $id_card );
	} else {
		return false;
	}
}
// 计算身份证校验码，根据国家标准GB 11643-1999
function idcardVerifyNumber($idcard_base) {
	if (strlen ( $idcard_base ) != 17) {
		return false;
	}
	// 加权因子
	$factor = array (
			7,
			9,
			10,
			5,
			8,
			4,
			2,
			1,
			6,
			3,
			7,
			9,
			10,
			5,
			8,
			4,
			2 
	);
	// 校验码对应值
	$verify_number_list = array (
			'1',
			'0',
			'X',
			'9',
			'8',
			'7',
			'6',
			'5',
			'4',
			'3',
			'2' 
	);
	$checksum = 0;
	for($i = 0; $i < strlen ( $idcard_base ); $i ++) {
		$checksum += substr ( $idcard_base, $i, 1 ) * $factor [$i];
	}
	$mod = $checksum % 11;
	$verify_number = $verify_number_list [$mod];
	return $verify_number;
}
// 将15位身份证升级到18位
function idcard15to18($idcard) {
	if (strlen ( $idcard ) != 15) {
		return false;
	} else {
		// 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特
		
		if (array_search ( substr ( $idcard, 12, 3 ), array (
				'996',
				'997',
				'998',
				'999' 
		) ) !== false) {
			$idcard = substr ( $idcard, 0, 6 ) . '18' . substr ( 

			$idcard, 6, 9 );
		} else {
			$idcard = substr ( $idcard, 0, 6 ) . '19' . substr ( 

			$idcard, 6, 9 );
		}
	}
	$idcard = $idcard . idcardVerifyNumber ( $idcard );
	return $idcard;
}
// 18位身份证校验码有效性检查
function idcardChecksum18($idcard) {
	if (strlen ( $idcard ) != 18) {
		return false;
	}
	$idcard_base = substr ( $idcard, 0, 17 );
	if (idcardVerifyNumber ( $idcard_base ) != strtoupper ( substr ( 

	$idcard, 17, 1 ) )) {
		return false;
	} else {
		return true;
	}
}

/**
 * 判断字符串是否是时间格式
 *
 * @param
 *        	$str
 */
function isDate($str) {
	$reg = '/^(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)$/';
	return preg_match ( $reg, $str );
}

/**
 * 生成订单号
 *
 * @return string
 */
function createOrderNumber() {
	$year_code = array (
			'A',
			'B',
			'C',
			'D',
			'E',
			'F',
			'G',
			'H',
			'I',
			'J',
			'K',
			'L',
			'M',
			'N',
			'O',
			'P',
			'Q',
			'R',
			'S',
			'T',
			'U',
			'V',
			'W',
			'X',
			'Y',
			'Z' 
	);
	$order_sn = $year_code [intval ( date ( 'Y' ) ) - 2013] . strtoupper ( dechex ( date ( 

	'm' ) ) ) . date ( 'd' ) . substr ( time (), - 5 ) . substr ( microtime (), 2, 5 ) . sprintf ( 

	'%02d', rand ( 0, 99 ) );
	return $order_sn;
}

/**
 * 下载远程文件，需要开启curl
 *
 * @param $url 远程文件路径        	
 * @param $savePath 保存路径        	
 * @param $fileName 保存文件名称        	
 * @param $type 获取远程文件方法
 *        	1：curl 0:Output
 */
function getFiles($url, $savePath, $fileName, $type = 0) {
	if (is_null ( trim ( $url ) )) {
		return false;
	}
	if (is_null ( trim ( $savePath ) )) {
		$savePath = "." . DIRECTORY_SEPARATOR;
	}
	// 文件路径最后加/
	if (0 !== strrpos ( $savePath, DIRECTORY_SEPARATOR )) {
		$savePath .= DIRECTORY_SEPARATOR;
	}
	// 查看保存目录是否存在，不存在则创建
	if (! file_exists ( $savePath ) && ! mkdir ( $savePath, 0777, true )) {
		return false;
	}
	// 获取远程文件所采用的方法。$type=1而且curl扩展开启的话用curl否则用output
	if ($type && extension_loaded ( "curl" )) {
		$ch = curl_init ();
		$timeout = 5;
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
		$content = curl_exec ( $ch );
	} else {
		ob_start ();
		readfile ( $url );
		$content = ob_get_contents ();
		ob_end_clean ();
	}
	$fp2 = @fopen ( $savePath . $fileName, 'a' );
	fwrite ( $fp2, $content );
	fclose ( $fp2 );
	unset ( $content, $url );
	return array (
			'file_name' => $fileName,
			'save_path' => $savePath . $fileName 
	);
}
/**
	判断是否POST提交
 */
function isPost() {
	if ($_SERVER ['REQUEST_METHOD'] == "POST") {
		return true;
	}
	return false;
}

// 做系统的话,可以用下面的代码,也是copy来的。
// PHP代码
function injectCheck($sqlStr) {
	return eregi ( 'select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sqlStr ); // 进行过滤
}

/**
	验证ID是否为数字
 */
function verifyId($id = 0) {
	$id = intval ( $id ); // 整型化
	return $id;
}
/**
 * 过滤sql注入
 *
 * @param unknown_type $content        	
 */
function sqlFilter($content) {
	if (! get_magic_quotes_gpc ()) {
		if (is_array ( $content )) {
			foreach ( $content as $key => $value ) {
				if (is_array ( $value )) {
					foreach ( $value as $key1 => $value1 ) 
					{
						$value [$key1] = addslashes ( $value1 );
						$value [$key1] = strSqlReplace ( $value1 );
					}
					$content [$key] = $value;
				} else {
					$content [$key] = addslashes ( $value );
					$content [$key] = strSqlReplace ( $value );
				}
			}
		} else {
			addslashes ( $content );
			$content = strSqlReplace ( $content );
		}
	} else {
		if (is_array ( $content )) {
			foreach ( $content as $key => $value ) {
				if (is_array ( $value )) {
					foreach ( $value as $key1 => $value1 ) 
					{
						$value [$key1] = strSqlReplace ( $value1 );
					}
					$content [$key] = $value;
				} else {
					$content [$key] = strSqlReplace ( $value );
				}
			}
		} else {
			$content = strSqlReplace ( $content );
		}
	}
	return $content;
}
function strSqlReplace($str) {
	if (! get_magic_quotes_gpc ()) { // 判断magic_quotes_gpc是否为打开
		$str = addslashes ( $str ); // 进行magic_quotes_gpc没有打开的情况对提交数据的过滤
	}
	$str = str_replace ( "_", "\_", $str ); // 把 '_'过滤掉
	$str = str_replace ( "%", "\%", $str ); // 把 '%'过滤掉
	$str = str_replace ( "and", "&#97;nd", $str );
	$str = str_replace ( "execute", "&#101;xecute", $str );
	$str = str_replace ( "update", "&#117;pdate", $str );
	$str = str_replace ( "count", "&#99;ount", $str );
	$str = str_replace ( "chr", "&#99;hr", $str );
	$str = str_replace ( "mid", "&#109;id", $str );
	$str = str_replace ( "master", "&#109;aster", $str );
	$str = str_replace ( "truncate", "&#116;runcate", $str );
	$str = str_replace ( "char", "&#99;har", $str );
	$str = str_replace ( "declare", "&#100;eclare", $str );
	$str = str_replace ( "select", "&#115;elect", $str );
	$str = str_replace ( "create", "&#99;reate", $str );
	$str = str_replace ( "delete", "&#100;elete", $str );
	$str = str_replace ( "insert", "&#105;nsert", $str );
	$str = str_replace ( "'", "&#39;", $str );
	$str = str_replace ( "\"", "&#34;", $str );
	$str = preg_replace ( '/<script>/i', '', $str );
	$str = preg_replace ( '/<\/script>/i', '', $str );
	$str = nl2br ( $str ); // 回车转换
	$str = trim ( $str );
	$str = htmlspecialchars ( $str ); // html标记转换
	return $str;
}

/**
 * 检查IP地址是否正确。
 */
function checkIpAddres($ipaddres) {
	return filter_var ( $ipaddres, FILTER_VALIDATE_IP );
}